<?php

class RequestsController extends Controller {
    /**
     * @var string the default layout for the views. Defaults to 'column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout='column2';

    /**
     * @var CActiveRecord the currently loaded data model instance.
     */
    private $_model;

    /**
     * @return array action filters
     */
    public function filters() {
        return array(
                'accessControl', // perform access control for CRUD operations
        );
    }


    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
                array('allow', // allow admin user to perform 'admin' and 'delete' actions
                        'actions'=>array('finReq','index','view','delete','delFinal','FetchedRequests','AvaliableRequests','FinalRequests','ChoosedRequests','createRequest','Apply'),
                        'roles'=>array('student'),
                ),
                array('allow', // allow admin user to perform 'admin' and 'delete' actions
                        'actions'=>array('admin','index','view'),
                        'roles'=>array('admin','professor'),
                ),
                array('deny',  // deny all users
                        'users'=>array('*'),
                ),
        );
    }


    /**
     * Displays a particular model.
     */
    public function actionView() {
        $this->render('view',array(
                'model'=>$this->loadModel(),
        ));
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model) {
        if(isset($_POST['ajax']) && $_POST['ajax']==='requests-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

    public function actionApply() {
        $request=new Requests;
        if(isset($_POST['Requests'])) {
            $coursework=CourseWorks::model()->findByPk($_GET['id']);
            $request->courseWork_id=$coursework->id;
            $request->student_id=Yii::app()->user->id;
            $request->coverletter=$_POST['Requests']['coverletter'];
            $request->archived=0;
            $request->save();
            $this->actionChoosedRequests();
        }
        else {

            $coursework=CourseWorks::model()->findByPk($_GET['id']);
            $this->render('Apply',array('cmodel'=>$coursework,'rmodel'=>$request));
        }

    }
    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     
    public function actionCreateRequest() {
        $request = new Requests;

        if (isset($_GET['id'])) {

            $criteria=new CDbCriteria;
            $criteria->condition='student_id=:id AND courseWork_id=:cid';
            $criteria->params=array(':id'=>Yii::app()->user->id,':cid'=>$_GET['id']);

            $count=Requests::model()->count($criteria);

            //if($count==0) {
            $request->courseWork_id=$_GET['id'];
            $request->student_id=Yii::app()->user->id;
            $request->save();
            $this->actionChoosedRequests();
            //   }
        }
        else {
            $this->actionAvaliableRequests();

        }


    }*/

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     */
    public function actionUpdate() {
        $model=$this->loadModel();

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if(isset($_POST['Requests'])) {
            $model->attributes=$_POST['Requests'];
            if($model->save())
                $this->redirect(array('view','id'=>$model->id));
        }

        $this->render('update',array(
                'model'=>$model,
        ));
    }


    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     */
    public function actionDelete() {
        if(Yii::app()->request->isPostRequest) {
            // we only allow deletion via POST request
            $this->loadModel()->delete();

            /**
             * Lists all models.
             */

            // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
            if(!isset($_GET['ajax']))
                $this->actionIndex();
        }
        else
            throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
    }


    /**
     * Lists all models.
     */
    public function actionIndex() {
        $criteria = new CDbCriteria;
        $criteria->condition ='studentid='.Yii::app()->user->id;
        $coursework=CourseWorks::model()->find($criteria);
        $student= Student::model()->findByPK(Yii::app()->user->id);
        $this->render('index',array('coursework'=>$coursework,'student'=>$student));
    }


    /**
     * Manages all models.
     */
    public function actionAdmin() {
        $model=new Requests('search');
        if(isset($_GET['Requests']))
            $model->attributes=$_GET['Requests'];

        $this->render('admin',array(
                'model'=>$model,
        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     */
    public function loadModel() {
        if($this->_model===null) {
            if(isset($_GET['id']))
                $this->_model=Requests::model()->findbyPk($_GET['id']);
            if($this->_model===null)
                throw new CHttpException(404,'The requested page does not exist.');
        }

        return $this->_model;
    }

    /*
     *Доступные темы
    */
    public function actionAvaliableRequests() {
        if($this->CheckFinal()){
        $student=Student::model()->findByPk(Yii::app()->user->id);
        $condition ='facultyid='.$student->faculty_id.' AND year='.$student->year.' AND studentid IS NULL';
        $dataProvider=new CActiveDataProvider('courseWorks',
                array('criteria'=>
                        array('condition'=>$condition,
                          'with'=>array('professor')
                        )
                )
        );       
            $this->render('avaliableRequests',array('dataProvider'=>$dataProvider));
        }else{$this->actionIndex();}
           
        }
        
    
    /*
     * Одобренные темы
    */
    public function actionFetchedRequests() {
        if($this->CheckFinal()){
        $condition ='student_id='.Yii::app()->user->id.' AND courseWork.choosed=1  AND archived=0';

        $dataProvider=new CActiveDataProvider('Requests',
                array('criteria'=>
                        array('condition'=>$condition,
                                'with'=>array('courseWork')
                        )
                )
        );
        $this->render('fetchedRequests',array('dataProvider'=>$dataProvider));
        }else{$this->actionIndex();}
    }

    /*
     *
    */
    public function actionFinalRequests() {
        $criteria = new CDbCriteria;


        $criteria->condition ='studentid='.Yii::app()->user->id;
        $coursework=CourseWorks::model()->find($criteria);

        $student= Student::model()->findByPK(Yii::app()->user->id);
        $this->render('index',array('coursework'=>$coursework,'student'=>$student));
    }
    /*
     *Выбранные темы
    */
    public function actionChoosedRequests() {
        if($this->CheckFinal()){
        $condition ='student_id='.Yii::app()->user->id.' AND archived=0';
        $dataProvider=new CActiveDataProvider('Requests',
                array('criteria'=>
                        array('condition'=>$condition,
                                'with'=>array('courseWork'))));
        $this->render('choosedRequests',array('dataProvider'=>$dataProvider));
        }else{$this->actionIndex();}

    }
    public function CheckFinal() {
        $criteria=new CDbCriteria;
        $criteria->condition='studentid='.Yii::app()->user->id;
        $count=CourseWorks::model()->count($criteria);
        
        if($count<1) {
            return true;
        }
        else {
            return false;
        }
    }
    /*
     *выбор итоговой темы
     */
    public function actionFinReq() {
        if($this->checkFinal()){
        //заносим id студента в итоговую тему работы
        $coursework=CourseWorks::model()->findByPK($_GET['id']);
        $coursework->studentid=Yii::app()->user->id;
        $coursework->save();

        //меняем все заявки студента из таблицы Requests
        $criteria = new CDbCriteria;
        $criteria->condition ='student_id='.Yii::app()->user->id;
        $reqs = Requests::model()->findAll($criteria);
        if($reqs !== null) {
            foreach ($reqs as $req) {
                $req->archived = '1';
                $req->save();
            }
           // $reqs->save();
        }

        $student= Student::model()->findByPK(Yii::app()->user->id);

        $this->render('index',array('coursework'=>$coursework,'student'=>$student));
        }else{$this->actionIndex();}
    }  
}
